package com.imooc.modular.controller;

import com.fasterxml.jackson.annotation.JsonView;
import com.imooc.modular.dto.User;
import com.imooc.modular.validator.Insert;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang.builder.ReflectionToStringBuilder;
import org.apache.commons.lang.builder.ToStringStyle;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@RestController
public class UserController {


    @GetMapping("/user")
    @JsonView(User.UserSimpleView.class)
    @ApiOperation(value = "获取用户列表", notes = "123")
    public List<User> query(@RequestParam(required = false) String userName) {

        ReflectionToStringBuilder.toString(userName, ToStringStyle.MULTI_LINE_STYLE);
        List<User> userList = new ArrayList<>(10);
        userList.add(new User("张三", "123", "1"));
        userList.add(new User("李四", "456", "2"));

        return userList;
    }

    @GetMapping("/user/{id:\\d+}")
    @JsonView(User.UserDetailView.class)
    public User getInfo(@PathVariable String id) {

        Date date = new Date(LocalDateTime.now().plusYears(1).atZone(ZoneId.systemDefault()).toInstant().getEpochSecond());
        return new User("123", "abc", id);

    }

    @PostMapping("/user")
    public User createUser(@Validated({Insert.class}) @RequestBody User user, BindingResult bindingResult) {

        if (bindingResult.hasErrors()) {
            bindingResult.getAllErrors().stream().forEach(error -> error.getDefaultMessage());
        }
        System.out.println(user.toString());
        return null;
    }

    @GetMapping("/me")
    public Object getCurrentUser() {
        return SecurityContextHolder.getContext().getAuthentication();
    }
    @GetMapping("/me1")
    public Object getCurrentUser(Authentication authentication) {
        return authentication;
    }
    @GetMapping("/me2")
    public Object getCurrentUser(@AuthenticationPrincipal UserDetails userDetails) {
        return userDetails;
    }


}
